<template>
  <div v-if="!switchFlag" class="supplier-examine-list">
    <div :class="{'mobile-top': showMobilePage}" class="title-top">
      <div>
        <Title title="审批记录" />
      </div>
      <el-tooltip placement="top">
        <div slot="content">
          <div>统计值公式说明</div>
          <div>1、审批完成金额：详情审批列表“已完成”状态金额之和</div>
          <div>2、已付款金额：详情审批列表“已付款”状态金额之和</div>
          <div>3、已审批未付款金额：（审批中或已完成）且未付款状态金额之和</div>
          <div>4、未审批未付款金额：总金额-（已付款金额+已审批未付款金额）</div>
        </div>
        <tipIcon is-diy class="ml5" />
      </el-tooltip>
    </div>
    <dataDisplay v-if="(process === 2 || process === 4)" :data-list="dataList" class="top-data" />
    <el-table
      v-if="examineList && examineList.items.length > 0"
      :data="examineList.items"
      :highlight-current-row="true"
      :current-row-key="currentRowKey"
      row-key="id"
      class="fb-table"
      header-cell-class-name="order-data-header-cell"
      @row-click="toCheck"
    >
      <el-table-column align="left" label="审批单号" min-width="200">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.examineId" class="item" effect="dark" placement="top-start">
            <div slot="content" style="max-width: 200px;">{{ scope.row.examineId }}</div>
            <div class="ellipsisOne" style="padding-left: 4px;">{{ scope.row.examineId }}</div>
          </el-tooltip>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="审批进度" min-width="90">
        <template slot-scope="scope">
          <div style="display:flex;align-items:center;">
            <span :style="{ backgroundColor: scope.row.examineColor }" class="dot"/>
            <span>{{ scope.row.examineStatus | examineStatus }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="right" label="结算金额(元)" min-width="130">
        <template slot-scope="scope">
          <PriceColumn :real-val="scope.row.settlementAmount" :price="scope.row.settlementAmount / 100" />
        </template>
      </el-table-column>
      <el-table-column align="right" label="实付金额(元)" min-width="130">
        <template slot="header" slot-scope="scope">
          <div class="dynamic-table-header">
            <span class="label" style="padding-right:10px;">{{ scope.column.label }}</span>
          </div>
        </template>
        <template slot-scope="scope">
          <div style="padding-right:10px;">
            <PriceColumn :real-val="scope.row.actualAmount" :price="scope.row.actualAmount / 100" />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="付款状态" width="90">
        <template slot-scope="scope">
          <div style="display:flex;align-items:center;">
            <span :style="{ backgroundColor: scope.row.paymentColor }" class="dot"/>
            <span>{{ scope.row.paymentStatus | examinePayStatus }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建人" min-width="100">
        <template slot-scope="scope">
          <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建时间" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <empty-placeholder v-else :empty-img="emptyDataIcon" image-size="100px" style="margin-bottom: 24px" />
    <el-row type="flex" justify="end" class="pagination-area">
      <el-pagination
        v-show="examineList.total > 10"
        :current-page="examineList.page"
        :page-size="examineList.perPage"
        :total="examineList.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import emptyDataIcon from '@/assets/empty-data-icon.png';
import chargeoffiIcon from '@/assets/chargeOffDetail/chargeoff_status.png';
import { examinePay, examineList, examineCancel } from '@/api/supplier';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import { examineStatus, examinePayStatus } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import TableOperate from './tableOperate';
import { showModal } from '@/utils/message';
import math from '@/utils/math';

export default {
  components: { Title, EmptyPlaceholder, TableOperate, dataDisplay },
  filters: { examineStatus, format, examinePayStatus },
  props: {
    settleId: {
      type: String | Number,
      default: null
    },
    isComplete: {
      type: Boolean,
      default: false
    },
    process: {
      type: Number,
      default: null
    },
    isCreator: {
      type: Boolean,
      default: true
    },
    operateData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isClosed: {// 是否已关闭
      type: Boolean,
      default: false
    },
    totalPrice: {
      type: Number,
      default: null
    },
    payAmount: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      emptyDataIcon,
      switchFlag: false,
      page: 1,
      perPage: 20,
      examineList: {
        items: [],
        total: 0,
        page: 1,
        perPage: 20
      },
      examineTypeColor: [{
        examineStatus: 0,
        examineColor: '#FD8546'
      }, {
        examineStatus: 1,
        examineColor: '#FD8546'
      }, {
        examineStatus: 2,
        examineColor: '#E02020'
      }, {
        examineStatus: 4,
        examineColor: '#31CC9C'
      }, {
        examineStatus: 3,
        examineColor: '#999999'
      }, {
        examineStatus: 5,
        examineColor: '#E02020'
      }],
      payTypeColor: [{
        paymentStatus: 0,
        paymentColor: '#FD8546'
      }, {
        paymentStatus: 1,
        paymentColor: '#31CC9C'
      }],
      currentRowKey: null, // 高亮行，值为每个审批单的id
      isExamineing: false, // 列表中存在有审批中的订单
      isExamined: false, // 列表中存在有已完成的订单
      chargeoffiIcon
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    settleTotalPrice() {
      return this.examineList.items.reduce((pre, next) => {
        return math.add(pre, (next.examineStatus === 4 ? (next.actualAmount / 100) : 0));
      }, 0);
    },
    paidAmount() {
      return this.examineList.items.reduce((pre, next) => {
        return math.add(pre, (next.paymentStatus ? (next.actualAmount / 100) : 0));
      }, 0);
    },
    bePaidAmount() {
      return this.examineList.items.reduce((pre, next) => {
        const tempStatus = (next.examineStatus === 1 || next.examineStatus === 4) && next.paymentStatus === 0;
        return math.add(pre, (tempStatus ? (next.actualAmount / 100) : 0));
      }, 0);
    },
    restAmount() {
      return math.subtract((this.totalPrice / 100), math.add(this.paidAmount, this.bePaidAmount));
    },
    dataList() {
      return [
        // { icon: chargeoffiIcon, label: '审批结算金额(总)', data: (this.settleTotalPrice / 100), unit: '元' },
        // { icon: chargeoffiIcon, label: '已付款金额(总)', data: this.payAmount / 100, unit: '元' },
        // { icon: chargeoffiIcon, label: '待付款金额(总)', data: (this.settleTotalPrice - this.payAmount) / 100, unit: '元' },
        { icon: chargeoffiIcon, label: '审批完成金额', data: this.settleTotalPrice, unit: '元' },
        { icon: chargeoffiIcon, label: '已付款金额', data: this.paidAmount, unit: '元' },
        { icon: chargeoffiIcon, label: '已审批未付款金额', data: this.bePaidAmount, unit: '元' },
        { icon: chargeoffiIcon, label: '未审批未付款金额', data: this.restAmount, unit: '元' }
      ];
    }
  },
  watch: {
    showMobilePage(val) {
      this.switchFlag = true;
      this.$nextTick(() => {
        this.switchFlag = false;
      });
    }
  },
  created() {
    this.getExamineList(true, true);
  },
  methods: {
    moneyFilter,
    hasRouteAuth,
    showApproverChangeBtn(status) {
      return status !== -1 && status !== 4;
    },
    // 审批列表
    getExamineList(reset = false, init = false) {
      if (reset) this.page = 1;
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      examineList(this.settleId, params).then(res => {
        const { id, fromInputInvoice, dimension } = this.$route.query;
        // 存在审批中状态 和 已完成
        this.isExamineing = res.data.items.some(i => i.examineStatus === 1);
        this.isExamined = res.data.items.some(i => i.examineStatus === 4);
        this.$emit('isExamin', this.isExamineing, this.isExamined);
        if (res.data.items.length && res.data.items.length) {
          // 获取创建时间最早的审批单id，发起审批将自动填充该审批单数据
          this.$emit('getFirstExamineId', res.data.items[res.data.items.length - 1].id);
          // 多条审批单默认高亮第一条
          res.data.items.length > 1 && !this.currentRowKey && (this.currentRowKey = res.data.items[0].id);
        }
        res.data.items.map((item, i) => {
          if (fromInputInvoice) { // 从进项发票跳转过来
            if (item.id === Number(id)) {
              item.isCheck = true;
              this.$emit('updateCurrentWithdrawInfo', { ...item, isExamineing: true });
            } else {
              item.isCheck = false;
            }
          } else if (dimension) { // 付款申请审批单维度跳转过来的
            if (item.id === Number(this.$route.params.id)) {
              item.isCheck = true;
              this.$emit('updateCurrentWithdrawInfo', { ...item, isExamineing: true });
            } else {
              item.isCheck = false;
            }
          } else {
            if (this.$route.query.isContinueApprove) { // 继续下一项审批的审批中项可能不在第一项
              item.isCheck = false;
              if (item.examineStatus === 1) {
                item.isCheck = true;
                this.$emit('updateCurrentWithdrawInfo', { ...item, isExamineing: true });
              }
            } else {
              item.isCheck = !i;
            }
          }
          const examineTypeColor = this.examineTypeColor.find(currentValue => item.examineStatus === currentValue.examineStatus);
          const payTypeColor = this.payTypeColor.find(currentValue => item.paymentStatus === currentValue.paymentStatus);
          item = Object.assign(item, examineTypeColor, payTypeColor);
          return item;
        });
        if (init) {
          this.$emit('examineListInit', res.data.items);
        }
        // 审批列表里要都是已完成/已作废，才能显示申请余额按钮
        const allStatus = res.data.items.every(i => {
          return i.examineStatus === 3 || i.examineStatus === 4;
        });
        if (allStatus) {
          const doneTotal = res.data.items.reduce((pre, next) => {
            return pre + (next.examineStatus === 4 ? (next.settlementAmount / 100) : 0);
          }, 0);
          this.$emit('emitExamine', allStatus, doneTotal);
        }
        this.examineList = res.data;
        this.page = res.data.page;
        this.perPage = res.data.perPage;
        this.$emit('setCreator', res.data.items.slice(0).map(el => el.creatorId));// 用于判断是否是创建人
      }).catch(err => {
        console.error(err);
      });
    },
    toCheck(row) {
      this.examineList.items.map(i => {
        i.isCheck = false;
        return i;
      });
      this.$nextTick(() => {
        row.isCheck = true;
      });
      this.$emit('updateCurrentWithdrawInfo', { ...row, isExamineing: this.isExamineing });
    },
    toPay(row) {
      showModal('请确认是否已支付？', '', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        examinePay(row.id).then(res => {
          this.$message.success('付款成功');
          this.getExamineList(true);
          this.$emit('updateDetail');
        }).catch(err => {
          console.error(err);
        });
      });
    },
    examineBack(item) {
      showModal('当前审批任务已完成，撤回后审批任务重新开始，请谨慎操作', '', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        iconClass: 'del-icon'
      }).then(() => {
        examineCancel({ id: item.id }).then(res => {
          if (res.code === 200) {
            this.$message.success('撤回成功');
            this.getExamineList(true);
            this.$emit('updateDetail');
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getExamineList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getExamineList();
    },
    againLaunch(row) {
      this.$emit('againLaunch', row);
    },
    toEdit(row) {
      this.$emit('toEdit', row);
    },
    handleApproverChange(id) {
      if (!id) {
        this.$message.warning('无法获取ID');
        return;
      }
      this.$emit('handleApproverChange', id);
    },
    isExamineCreator(item) {
      return this.userInfo.id === item.creatorId;
    },
    moreBtnShow(item) {
      const showApprover = this.showApproverChangeBtn(item.examineStatus); // 审批转交
      const payAuth = item.examineStatus === 4 && !this.isComplete && !item.paymentStatus && hasRouteAuth('medium:supplierAudit:pay'); // 付款
      const backAuth = process !== 4 && item.examineStatus === 4 && hasRouteAuth('medium:supplierAudit:higherRecall'); // 撤回
      const againCreate = (item.examineStatus === 3 || item.examineStatus === 4) && !this.isComplete && !this.isExamineing && this.isCreator; // 再次发起（复制）
      const editAuth = (item.examineStatus === 2 || item.examineStatus === 5) && !this.isComplete && !this.isExamineing && this.isExamineCreator(item); // 修改
      let arr = [showApprover, payAuth, backAuth, againCreate, editAuth];
      arr = arr.filter(i => !!i);
      return arr.length > 3;
    }
  }
};
</script>
<style lang="scss" scoped>
.supplier-examine-list {
  margin-bottom: 32px;
  .title-top {
    display: flex;
    // justify-content: flex-start;
    align-items: center;
    margin: 16px 0 12px;
  }
  .top-data {
    margin-bottom: 16px;
  }
  .order-data-header-cell {
    .cell {
      color: '#141C3D';
    }
  }
  &::v-deep {
    thead {
      .order-data-header-cell:first-child {
        .cell {
          padding-left: 13px;
        }
      }
    }
    .mobile-data-item {
      flex: 1
    }
  }
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
.mobile-top {
  flex-wrap: wrap;
  .top-data {
    margin-left: 0 !important;
    margin-top: 10px !important;
  }
}
</style>
